Option Strict On
Option Explicit On 

Imports System
Imports System.IO
Imports System.Drawing
Imports System.ComponentModel

Namespace xpComponent.Form
    Public Class RemoveButton
        Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Integer, ByVal revert As Integer) As Integer
        Private Declare Function GetMenuItemCount Lib "user32" (ByVal menu As Integer) As Integer
        Private Declare Function RemoveMenu Lib "user32" (ByVal menu As Integer, ByVal position As Integer, ByVal flags As Integer) As Integer
        Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As Integer) As Integer
        Private Declare Function FormatMessageA Lib "kernel32" (ByVal flags As Integer, ByRef source As Object, ByVal messageID As Integer, ByVal languageID As Integer, ByVal buffer As String, ByVal size As Integer, ByRef arguments As Integer) As Integer

        Private Const MF_BYPOSITION As Integer = &H400
        Private Const MF_DISABLED As Integer = &H2

        Private Sub New()

        End Sub

        Public Shared Sub Disable(ByVal form As System.Windows.Forms.Form)
            Dim menu As Integer = GetSystemMenu(form.Handle.ToInt32, 0)
            Dim count As Integer = GetMenuItemCount(menu)
            If RemoveMenu(menu, count - 1, MF_DISABLED Or MF_BYPOSITION) = 0 Then
                Throw New Exception(FormatMessage(Err.LastDllError))
            Else
                If DrawMenuBar(form.Handle.ToInt32) = 0 Then
                    Throw New Exception(FormatMessage(Err.LastDllError))
                End If
            End If
        End Sub

        Public Shared Function FormatMessage(ByVal [error] As Integer) As String
            Const FORMAT_MESSAGE_FROM_SYSTEM As Short = &H1000
            Const LANG_NEUTRAL As Short = &H0
            Dim buffer As String = Space(999)
            FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, [error], LANG_NEUTRAL, buffer, 999, 0)
            buffer = Replace(Replace(buffer, Chr(13), ""), Chr(10), "")
            Return buffer.Substring(0, buffer.IndexOf(Chr(0)))
        End Function
    End Class
End Namespace